import React, { useState, useEffect } from 'react';

// 组件
import TabNav from './components/TabNav';
import DataTable from './components/DataTable';

// 工具和常量
import { fetchTableData } from './service';
import { TAB_ITEMS, DEFAULT_PAGINATION } from './constants';

// 类型
import { TableItem, PaginationParams } from './types';

// 样式
import style from './index.less';

const Home: React.FC = () => {
  // 状态定义
  const [activeTab, setActiveTab] = useState('6'); // 默认选中"重要业务系统投产规划(中心)"
  const [tableData, setTableData] = useState<TableItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<PaginationParams>(DEFAULT_PAGINATION);

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      const response = await fetchTableData({
        tabKey: activeTab,
        page: pagination.current,
        pageSize: pagination.pageSize
      });
      
      setTableData(response.list);
      setPagination({
        ...pagination,
        total: response.total
      });
    } catch (error) {
      console.error('加载数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 标签页切换处理
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setPagination({ ...pagination, current: 1 });
  };

  // 分页改变处理
  const handlePageChange = (page: number, pageSize?: number) => {
    setPagination({
      ...pagination,
      current: page,
      pageSize: pageSize || pagination.pageSize
    });
  };

  // 监听tab和分页变化，重新加载数据
  useEffect(() => {
    loadData();
  }, [activeTab, pagination.current, pagination.pageSize]);

  return (
    <div className={style['home-container']}>
      {/* 顶部导航 */}
      <TabNav 
        items={TAB_ITEMS} 
        activeKey={activeTab} 
        onChange={handleTabChange} 
      />

      {/* 主内容区 */}
      <div className={style['content-wrapper']}>
        <DataTable 
          data={tableData}
          loading={loading}
          pagination={pagination}
          onPageChange={handlePageChange}
        />
      </div>
    </div>
  );
};

export default Home;
